package at.ac.univie.zsu.aguataplan.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.hibernate.Hibernate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import at.ac.univie.zsu.aguataplan.domain.Team;

/**
 * @author gerry
 * 
 */
@Repository
public class TeamDaoBean implements TeamDao {

	@PersistenceContext
	transient EntityManager em;

	@Autowired
	private Dao dao;

	// ----------------------------------------------------
	// CONSTRUCTOR
	// ----------------------------------------------------

	public TeamDaoBean() {

	}

	// ----------------------------------------------------
	// METHODS
	// ----------------------------------------------------

	@Override
	@Transactional
	public void cleanTeam() throws Exception {
		List<Team> teams = dao.findAll(Team.class);

		for (Team team : teams) {
			deleteTeam(team.getId());
		}

	}

	// --------------

	@Override
	public Team addTeam(Team team) throws Exception {
		dao.persist(team);
		return team;
	}

	@Override
	public void deleteTeam(long id) throws Exception {
		dao.remove(Team.class, id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Team> getTeamList() throws Exception {
		List<Team> teams;
		teams = em.createQuery("SELECT o FROM " + Team.class.getName() + " o ORDER BY name").getResultList();

		return teams;
	}

	@Override
	@Transactional
	public Team getTeam(long id) throws Exception {
		Team team;
		team = em.find(Team.class, id);

		Hibernate.initialize(team.getRefClub().getRefTeam());

		return team;
	}

	@Override
	public Team mergeTeam(Team team) throws Exception {
		Team t;
		t = dao.merge(team);

		return t;
	}

	// ----------------------------------------------------
	// GETTER & SETTER
	// ----------------------------------------------------

	public Dao getDao() {
		return dao;
	}

	public void setDao(Dao dao) {
		this.dao = dao;
	}

}
